package com.liangjie.upload;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@SuppressWarnings("serial")
public class CommonsUpload extends HttpServlet {

	/**
	 * 使用Apache commons组建实现文件上传
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 创建文件上传工厂类
		FileItemFactory factory = new DiskFileItemFactory();
		// 创建文件上传核心类对象
		ServletFileUpload upload = new ServletFileUpload(factory);
		// 判断当前表单是否为文件上传表单
		if (upload.isMultipartContent(request)) {
			// 把请求数据转换为FileItem对象集合
			try {
				List<FileItem> list = upload.parseRequest(request);
				for (FileItem item : list) {
					// 判断：是普通表单项还是文件上传表单
					if (item.isFormField()) {
						// 普通表单
						String filedName = item.getFieldName(); // name
						String content = item.getString();// value
					} else {
						// 文件上传表单
						String filedName = item.getFieldName(); // name
						String contentType = item.getContentType(); // 文件类型
						String name = item.getName(); // 文件名
						InputStream in = item.getInputStream(); // 文件流
						System.out.println(in);
					}
				}
			} catch (FileUploadException e) {
				e.printStackTrace();
			}

		} else {
			System.out.println("当前表单不是文件上传表单！");
		}
	}

}
